package MyFitnessPlate.TestApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import MyFitnessPlate.DataSet.ParsedWeightDataSet;
import MyFitnessPlate.Handler.GoalWeightHandler;
import MyFitnessPlate.Handler.WeightHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class GoalsActivity extends Activity {
	
	private Double userWeight;
    private Double goalWeight;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goals_screen);
        
        final TextView goalMessage = (TextView) findViewById(R.id.goal_status);
    	final TextView currentWeightText = (TextView) findViewById(R.id.current_weight);
    	final TextView goalWeightText = (TextView) findViewById(R.id.goal_weight);
    	final Button weightGoalButton = (Button) findViewById(R.id.weight_goal_button);
        //Get the goal weight.
        getGoalWeight();
        
        //Set the current values of the goal and current weights.
        getWeightEntry();

        currentWeightText.setText("Current Weight: "+userWeight+" lbs.");
        if(goalWeight == null){
        	goalWeightText.setText("");
        	goalMessage.setText("No goal weight has been set. Go ahead and set one.");
        } else {
        	goalWeightText.setText("Goal Weight: "+goalWeight+" lbs.");
        	determineIfGoalIsMet(goalMessage);
        }

        weightGoalButton.setText("Change goal");	//This allows us to change the text here.
        weightGoalButton.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
        		try {
        			EditText newGoalWeight = (EditText)findViewById(R.id.weight_goal_text);
            		String newGoalWeightString = newGoalWeight.getText().toString().trim();
	        		URL url = new URL("http://myfitnessplate.com/api/" +
	        				"edit-goal/username/"+GoalsActivity.this.getParent().getIntent().getExtras().getString("userName")+
	        				"/goal/"+newGoalWeightString+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
	        		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	        		in.close();
	        		//Notify them of the 
	        		final AlertDialog alertDialog = new AlertDialog.Builder(GoalsActivity.this).create();
                	alertDialog.setTitle("Goal set!");
                	alertDialog.setMessage("The new goal you entered has been set!");
                	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                		public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); }
                	});
                	alertDialog.show();
                	
                	//Set the goal weight again.
                	getGoalWeight();
                	goalWeightText.setText("Goal Weight: "+goalWeight+" lbs.");
                	determineIfGoalIsMet(goalMessage);
	        	} catch (MalformedURLException e) {
	        		handleError("URL error", "URL is incorrect", e);
	        	} catch (IOException e) {
	        		handleError("IO error", "Check files", e);
	        	}
        	}
        });
    }
    
	/**
	 * This method gets the goal weight from the server. This can be used to tell what the user's goal is.
	 */
    private void getGoalWeight(){
    	try {
    		String userName = getParent().getIntent().getExtras().getString("userName");
    		URL url = new URL("http://myfitnessplate.com/api/fetch-goal/username/"+userName+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
    		/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			GoalWeightHandler myGoalWeightHandler = new GoalWeightHandler();
			xr.setContentHandler(myGoalWeightHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			if(myGoalWeightHandler.getParsedData().getGoal().equalsIgnoreCase("none")){
				//This is a default goal weight for new accounts or accounts with no goal weight.
				goalWeight = 150.0;
			} else {
			goalWeight = Double.parseDouble(myGoalWeightHandler.getParsedData().getGoal());}
		} catch (MalformedURLException e) {
			handleError("URL error", "URL is incorrect", e);
		} catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
    }
    
    private void determineIfGoalIsMet(TextView goalMessage){
		if(userWeight <= goalWeight) {
			goalMessage.setText("You've reached your goal!\nReady to set another?");
    	} else {
    		goalMessage.setText("You're on your way!\nDo you need to modify your goal?");
    	}
    }
    
    /**
     * This method is used to handle errors by sending the message to the log
     * and printing the exception.
     * @param tag
     * @param message
     * @param e
     */
    private void handleError(String tag, String message, Exception e) {
		Log.d(tag, message);
		e.printStackTrace();
	}
    
    /**
     * This method allows the food entries to be loaded from the web site.
     */
    private void getWeightEntry(){
    	try {
    		String userName = getParent().getIntent().getExtras().getString("userName");
			URL url = new URL("http://myfitnessplate.com/api/fetch-weight-log/username/" + userName +
							  "/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			WeightHandler myWeightHandler = new WeightHandler();
			xr.setContentHandler(myWeightHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			ArrayList<ParsedWeightDataSet> wds = myWeightHandler.getParsedData();
			userWeight = wds.get(0).getWeight();
		} catch (MalformedURLException e) {
			handleError("URL error", "URL is incorrect", e);
		} catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
	}
    
    public void onResume(){
    	super.onResume();
    	//Get the current weight.
    	getWeightEntry();

    	//Update the current weight information.
    	final TextView currentWeightText = (TextView) findViewById(R.id.current_weight);
    	currentWeightText.setText("Current Weight: "+ userWeight +" lbs.");
    	
    	//Change the goal message depending on the information that is available.
    	final TextView goalMessage = (TextView) findViewById(R.id.goal_status);
    	determineIfGoalIsMet(goalMessage);
    }
    
    public void onRestart(){
    	super.onRestart();
    	onResume();
    }
}